package com.ocom.webapi.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.constant.WebApiServiceUrl;
import com.ocom.common.entity.master.EntityFileDownloadInfo;
import com.ocom.common.entity.mjrecode.MjRecord;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.simple.StudentExcelRequest;
import com.ocom.common.request.xfrecde.NotMealRecodeRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.response.web.ExcelApplyRequest;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.DateUtil;
import com.ocom.common.utils.RandomUtil;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.utils.excel.SXSSFWORKBookUtils;
import com.ocom.common.vo.recode.AccessRecordVo;
import com.ocom.common.vo.webapi.PageVO;
import com.ocom.security.authentication.YoCiUser;
import com.ocom.security.utils.SecurityUtils;
import com.ocom.webapi.feign.AccessClientService;
import com.ocom.webapi.feign.MinioClientService;
import com.ocom.webapi.feign.MjRecodeClientService;
import com.ocom.webapi.feign.MqSimpleService;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;


@RefreshScope
@RestController
public class ExcelExposeController {

	@Value("${excel.dir}")
	String excelPath;

	@Autowired
	private MinioClientService minioClientService;

	@Autowired
	AccessClientService accessClientService;

	@Autowired
	MqSimpleService mqSimpleService;

	@Autowired
	private MjRecodeClientService mjRecodeClientService;




	@SuppressWarnings("resource")
	@PostMapping(WebApiServiceUrl.URL_saveExcelHandle)
	public Result getExcel(@RequestBody @Valid ExcelApplyRequest excelApplyRequest) {
		long startTime = System.currentTimeMillis();

		String filePath = excelPath+ RandomUtil.getRandomString(32) +".xlsx";
		File file=new File(filePath);

		EntityFileDownloadInfo entityFileDownloadInfo=new EntityFileDownloadInfo();
		entityFileDownloadInfo.setId(excelApplyRequest.getId().longValue());

		//创建一个文件
		try {
			//创建Excel文件薄
			HSSFWorkbook workbook=new HSSFWorkbook();
			//创建工作表sheeet
			workbook.createSheet();

			//判断文件或文件夹是否存在
			boolean flag = file.exists();
			if(flag)
			{
				//文件存在就要删除文件
				file.delete();
			}

			file.createNewFile();
			FileOutputStream stream= FileUtils.openOutputStream(file);
			workbook.write(stream);
			stream.close();
		}catch (Exception e){
			e.printStackTrace();
		}finally {

		}

		SXSSFWorkbook sxssfWorkbook = null;
		BufferedOutputStream outputStream = null;
		try {
			//这样表示SXSSFWorkbook只会保留100条数据在内存中，其它的数据都会写到磁盘里，这样的话占用的内存就会很少
			sxssfWorkbook = new SXSSFWorkbook(SXSSFWORKBookUtils.getXSSFWorkbook(filePath),100);
			//获取第一个Sheet页
			SXSSFSheet sheet = sxssfWorkbook.getSheetAt(0);

			AccessRecordVo accessRecordVo=new AccessRecordVo();
			accessRecordVo.setBeginTime(excelApplyRequest.getBeginTime());
			accessRecordVo.setEndTime(excelApplyRequest.getEndTime());
			accessRecordVo.setComId(excelApplyRequest.getComId());
			accessRecordVo.setPage(1);
			accessRecordVo.setSize(1);

			accessRecordVo.setPCode(excelApplyRequest.getPCode());
			accessRecordVo.setAreaNo(excelApplyRequest.getAreaNo());
			accessRecordVo.setPId(excelApplyRequest.getPId());
			accessRecordVo.setPName(excelApplyRequest.getPName());
			accessRecordVo.setCodeColor(excelApplyRequest.getCodeColor());
			accessRecordVo.setParaSum(excelApplyRequest.getParaSum());
			accessRecordVo.setPType(excelApplyRequest.getPType());
			accessRecordVo.setOpenType(excelApplyRequest.getOpenType());
			accessRecordVo.setRegionId(excelApplyRequest.getRegionId());
//			accessRecordVo.setYctRetcode("200");


			Result result = mjRecodeClientService.GetAccessRecord(accessRecordVo);


			PageVO mjRecords = JSON.parseObject(JSON.toJSONString(result.getData()),PageVO.class);

			//下载失败 无数据
			if(mjRecords.getTotal()<=0){
				//TODO
				entityFileDownloadInfo.setStatus(2l);
				entityFileDownloadInfo.setRemark("无有效记录");
				accessClientService.UpdateFileStatus(entityFileDownloadInfo);

				return ResultUtil.error(ResultEnum.Err_4011);
			}

			int a = mjRecords.getTotal();
			int b = 500;
			BigDecimal aBig = new BigDecimal(a);
			BigDecimal bBig = new BigDecimal(b);
			//向上取整
			Integer pages =   (int)Math.ceil(aBig.divide(bBig).doubleValue());

			SXSSFRow row0 = sheet.createRow(0);
			row0.createCell(0).setCellValue("id");
			row0.createCell(1).setCellValue("部门名称");
			row0.createCell(2).setCellValue("片区id");
			row0.createCell(3).setCellValue("片区名称");
			row0.createCell(4).setCellValue("区域Id");
			row0.createCell(5).setCellValue("区域名称");
			row0.createCell(6).setCellValue("用户Id");
			row0.createCell(7).setCellValue("身份证");
			row0.createCell(8).setCellValue("姓名");
			row0.createCell(9).setCellValue("手机号");
			row0.createCell(10).setCellValue("设备Id");
			row0.createCell(11).setCellValue("设备号");
			row0.createCell(12).setCellValue("开门时间");
			row0.createCell(13).setCellValue("开门状态");
			row0.createCell(14).setCellValue("进出");
			row0.createCell(15).setCellValue("机器返回状态");
			row0.createCell(16).setCellValue("相关原因");
			row0.createCell(17).setCellValue("码颜色");
			row0.createCell(18).setCellValue("码时间");
			row0.createCell(19).setCellValue("核酸结果");
			row0.createCell(20).setCellValue("核酸时间");
			row0.createCell(21).setCellValue("疫苗针数");
			row0.createCell(22).setCellValue("疫苗时间");
			row0.createCell(23).setCellValue("体温");
			row0.createCell(24).setCellValue("头像");
			row0.createCell(25).setCellValue("月份");
			row0.createCell(26).setCellValue("创建时间");

			for (int i = 0; i < pages; i++) {

				AccessRecordVo accessRecordVo1=new AccessRecordVo();
				accessRecordVo1.setBeginTime(excelApplyRequest.getBeginTime());
				accessRecordVo1.setEndTime(excelApplyRequest.getEndTime());
				accessRecordVo1.setComId(excelApplyRequest.getComId());
				accessRecordVo1.setPage(i+1);
				accessRecordVo1.setSize(500);

				accessRecordVo1.setPCode(excelApplyRequest.getPCode());
				accessRecordVo1.setAreaNo(excelApplyRequest.getAreaNo());
				accessRecordVo1.setPId(excelApplyRequest.getPId());
				accessRecordVo1.setPName(excelApplyRequest.getPName());
				accessRecordVo1.setCodeColor(excelApplyRequest.getCodeColor());
				accessRecordVo1.setParaSum(excelApplyRequest.getParaSum());
				accessRecordVo1.setPType(excelApplyRequest.getPType());
				accessRecordVo1.setOpenType(excelApplyRequest.getOpenType());
				accessRecordVo1.setRegionId(excelApplyRequest.getRegionId());
//				accessRecordVo1.setYctRetcode("200");

				Result result1 = mjRecodeClientService.GetAccessRecord(accessRecordVo1);

				PageVO mjRecords1 = JSON.parseObject(JSON.toJSONString(result1.getData()),PageVO.class);

				int  z =0;
				for (Object o:mjRecords1.getRecords()){
					MjRecord mjRecord= JSON.parseObject(JSON.toJSONString(o),MjRecord.class);
					z++;
					SXSSFRow row = sheet.createRow(i * 500 + z);

					row.createCell(0).setCellValue(mjRecord.getId());
					row.createCell(1).setCellValue(CommonUtil.NulltoEmpty(mjRecord.getDeptName()));
					row.createCell(2).setCellValue(CommonUtil.NulltoEmpty(mjRecord.getRegionId()));
					row.createCell(3).setCellValue(CommonUtil.NulltoEmpty(mjRecord.getRegionName()));
					row.createCell(4).setCellValue(CommonUtil.NulltoEmpty(mjRecord.getAreaId()));
					row.createCell(5).setCellValue(CommonUtil.NulltoEmpty(mjRecord.getAreaName()));
					row.createCell(6).setCellValue(CommonUtil.NulltoEmpty(mjRecord.getPId()));
					row.createCell(7).setCellValue(CommonUtil.NulltoEmpty(mjRecord.getPCode()));
					row.createCell(8).setCellValue(CommonUtil.NulltoEmpty(mjRecord.getPName()));
					row.createCell(9).setCellValue(CommonUtil.NulltoEmpty(mjRecord.getPPhone()));
					row.createCell(10).setCellValue(CommonUtil.NulltoEmpty(mjRecord.getDeviceId()));
					row.createCell(11).setCellValue(CommonUtil.NulltoEmpty(mjRecord.getDeviceNo()));
					row.createCell(12).setCellValue(DateUtil.getDateTime(mjRecord.getOpenTime()));
					if(mjRecord.getOpenState()==1){
						row.createCell(13).setCellValue("开门");
					}else if(mjRecord.getOpenState()==2){
						row.createCell(13).setCellValue("关门");
					}else{
						row.createCell(13).setCellValue("拉取");
					}

					row.createCell(14).setCellValue(mjRecord.getOpenType());
					if(mjRecord.getOpenType()==0){
						row.createCell(14).setCellValue("离开");
					}else if(mjRecord.getOpenType()==1){
						row.createCell(14).setCellValue("进入");
					}


					row.createCell(15).setCellValue(CommonUtil.NulltoEmpty(mjRecord.getYctRetcode()));
					row.createCell(16).setCellValue(CommonUtil.NulltoEmpty(mjRecord.getData()));
					row.createCell(17).setCellValue(CommonUtil.NulltoEmpty(mjRecord.getCodeColor()));
					row.createCell(18).setCellValue(DateUtil.getDateTime(mjRecord.getColorTime()));
					row.createCell(19).setCellValue(CommonUtil.NulltoEmpty(mjRecord.getHsResult()));
					row.createCell(20).setCellValue(DateUtil.getDateTime(mjRecord.getHsTime()));
					row.createCell(21).setCellValue(CommonUtil.NulltoEmpty(mjRecord.getYmNum()));
					row.createCell(22).setCellValue(DateUtil.getDateTime(mjRecord.getYmTime()));
					row.createCell(23).setCellValue(CommonUtil.NulltoEmpty(mjRecord.getTemperature()));
					row.createCell(24).setCellValue(CommonUtil.NulltoEmpty(mjRecord.getAvatarUrl()));
					row.createCell(25).setCellValue(mjRecord.getMonthValue());
					row.createCell(26).setCellValue(DateUtil.getDateTime(mjRecord.getCreateTime()));
				}

//				for (int z = 1; z < 101; z++) {
//					SXSSFRow row = sheet.createRow(i * 100 + z);
//					for (int j = 0; j < 10; j++) {
//						row.createCell(j).setCellValue("你好：" + j);
//					}
//				}

			}

			outputStream = new BufferedOutputStream(new FileOutputStream(filePath));
			sxssfWorkbook.write(outputStream);
			outputStream.flush();
			sxssfWorkbook.dispose();// 释放workbook所占用的所有windows资源
		} catch (IOException e) {
			e.printStackTrace();

			entityFileDownloadInfo.setStatus(2l);
			accessClientService.UpdateFileStatus(entityFileDownloadInfo);

			return ResultUtil.error(ResultEnum.Err_4011);
		}finally {
			if(outputStream!=null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		File file1=new File(filePath);
//		MultipartFile multipartFile=FileUtil.getMultipartFile(file1);
		Result result = minioClientService.upload(file1);
		//删除本地
		file.delete();
		if(result.getCode()!=200){
			//更改状态 失败
			entityFileDownloadInfo.setStatus(2l);
			accessClientService.UpdateFileStatus(entityFileDownloadInfo);
			return ResultUtil.error(ResultEnum.Err_4012);
		}else{
			JSONObject jsonObject =JSON.parseObject(JSON.toJSONString( result.getData()));
			entityFileDownloadInfo.setStatus(1l);
			entityFileDownloadInfo.setUrl(jsonObject.getString("imageUrl"));
			accessClientService.UpdateFileStatus(entityFileDownloadInfo);
			//更改状态 成功
		}
		long endTime = System.currentTimeMillis();
		System.out.println(endTime-startTime);
		return ResultUtil.success();
	}


	@PostMapping(WebApiServiceUrl.URL_sendExcelApply)
	public Result sendExcelApply(@RequestBody @Valid ExcelApplyRequest excelApplyRequest) {
		EntityFileDownloadInfo entityFileDownloadInfo=new EntityFileDownloadInfo();
		if(excelApplyRequest.getPId()!=null){
			entityFileDownloadInfo.setPId(excelApplyRequest.getPId().longValue());
		}
		entityFileDownloadInfo.setPId(excelApplyRequest.getAdminId().longValue());
		entityFileDownloadInfo.setName("门禁记录");
		if(!CommonUtil.isNull(excelApplyRequest.getName())){
			entityFileDownloadInfo.setName(excelApplyRequest.getName());
		}

		entityFileDownloadInfo.setStatus(0l);
		Result result=accessClientService.SendExcelApply(entityFileDownloadInfo);
		if(result.getCode()!=200){
			return ResultUtil.error(ResultEnum.Err_4013);
		}
		excelApplyRequest.setId((Integer)result.getData());
		mqSimpleService.ExcelApply(excelApplyRequest);

		return ResultUtil.success();
	}



	@PostMapping(WebApiServiceUrl.URL_studentPageApply)
	public Result studentExcelApply(@RequestBody StudentExcelRequest request) {
		EntityFileDownloadInfo entityFileDownloadInfo=new EntityFileDownloadInfo();

		entityFileDownloadInfo.setPId(request.getAdminId().longValue());
		entityFileDownloadInfo.setName("人员导出");
		entityFileDownloadInfo.setRemark(JSON.toJSONString(request));
		entityFileDownloadInfo.setStatus(0l);
		Result result=accessClientService.SendExcelApply(entityFileDownloadInfo);
		if(result.getCode()!=200){
			return ResultUtil.error(ResultEnum.Err_4013);
		}
		request.setId((Integer)result.getData());
		mqSimpleService.StudentExcel(request);

		return ResultUtil.success();
	}

	@PostMapping(WebApiServiceUrl.URL_notMealRecodeApply)
	public Result notMealRecodeApply(@RequestBody NotMealRecodeRequest request){
		YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
		EntityFileDownloadInfo entityFileDownloadInfo=new EntityFileDownloadInfo();

		entityFileDownloadInfo.setPId(yoCiUser.getId().longValue());
		entityFileDownloadInfo.setName("未就餐人员导出");
		entityFileDownloadInfo.setRemark(JSON.toJSONString(request));
		entityFileDownloadInfo.setStatus(0l);
		Result result=accessClientService.SendExcelApply(entityFileDownloadInfo);
		if(result.getCode()!=200){
			return ResultUtil.error(ResultEnum.Err_4013);
		}

		return ResultUtil.success();
	}


}
